<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>购物车</title>
  <style>
    thead {
      background-color: #f5f5f5;
    }

    th,
    td {
      border: 1px solid #aaa;
      padding: 8px 12px;
      text-align: center;
    }
  </style>
</head>

<body>
  <table>
    <thead>
      <tr>
        <th>编号</th>
        <th>书籍名称</th>
        <th>出版日期</th>
        <th>价格</th>
        <th>购买数量</th>
        <th>操作</th>
      </tr>
    </thead>
    <tbody>

    </tbody>
  </table>
  <h2 class="price">总价格:¥<span class="price-count">0</span></h2>
  <script>
    //1.先拿到数据
    let books = [
      {
        id: 1,
        name: '《算法导论》',
        date: '2006-09',
        price: 85.0,
        count: 3,
      },
      {
        id: 2,
        name: '《UNIX编程艺术》',
        date: '2006-02',
        price: 59.0,
        count: 2,
      },
      {
        id: 3,
        name: '《编程珠玑》',
        date: '2008-10',
        price: 39.0,
        count: 5,
      },
      {
        id: 4,
        name: '《代码大全》',
        date: '2006-03',
        price: 128.0,
        count: 8,
      },
    ];
    //获取元素
    let tbody = document.querySelector('tbody');
    let priceCount = document.querySelector('.price-count');
    var rows = tbody.rows;//获取行对象
    //运行代码
    for (let i = 0; i < books.length; i++) {
      tbody.innerHTML += `
      <tr>
          <td>${books[i].id}</td>
          <td>${books[i].name}</td>
          <td>${books[i].date}</td>
          <td>${books[i].price}</td>
          <td>${books[i].count}</td>
          <td>
            <button class='del'>删除</button>
          </td>
        </tr>
      `
    }
    //在页面渲染之后计算所有总价=单价*数量
    let sumall = 0;
    for (let j = 0; j < rows.length; j++) {
      let num = rows[j].children[3].innerHTML;
      let count = rows[j].children[4].innerHTML;
      sumall += num*count;
      priceCount.innerHTML = sumall;
    }
    //每次点击之后删除那行，并且会重新渲染总价
    tbody.addEventListener('click', (e) => {
      if (e.target.className === 'del') {
        e.target.parentNode.parentNode.remove();
        sumall -= e.target.parentNode.parentNode.children[3].innerHTML * e.target.parentNode.parentNode.children[4].innerHTML;
        priceCount.innerHTML = sumall;
      }
    });
  </script>
</body>

</html>